package com.yl.applicationsecurity.filter;

/**
 * @author 鹤仙问鹿仙
 * @program: Application-security
 * @description:
 * @date 2025-01-14 15:14:38
 */

import com.yl.applicationsecurity.pojo.Result;
import com.yl.applicationsecurity.utils.SignatureUtil;
import org.springframework.beans.factory.annotation.Value;


import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;


@WebFilter(urlPatterns = {"/inspectionConfiguration/getList", "/inspection/insert","/componentUnauthorized/insert","/inspection/insert","/assets/insert"},filterName = "SignatureValidationFilter")
public class SignatureValidationFilter implements Filter {

    // 密钥，可以通过配置文件或其他方式加载
    @Value("${security.signature.secret-key:defaultSecretKey}")
    private  String SECRET_KEY;


    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        // 可选择性实现初始化逻辑
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
            throws IOException, ServletException {
        //HttpServletRequest httpRequest = (HttpServletRequest) request;
        HttpServletRequest httpRequest = (HttpServletRequest) request;
        HttpServletResponse httpResponse = (HttpServletResponse) response;

        // 获取请求参数
        Map<String, String> params = getRequestParams(httpRequest);

        // 获取签名（通常通过请求头或参数传递）
        String signature = httpRequest.getHeader("Signature");
        if (signature == null || signature.isEmpty()) {
            httpResponse.setStatus(401); // 设置 HTTP 状态码
            httpResponse.setContentType("application/json"); // 设置返回类型为 JSON

            // 写入响应内容
            try (PrintWriter writer = httpResponse.getWriter()) {
                writer.write("{\"error\":\"Missing signature\"}");
                writer.flush();
            }
            throw new ServletException("缺少签名");
        }

        // 验证签名
        System.out.println("签名的值："+SECRET_KEY);
        boolean isValid = SignatureUtil.verifySignature(params, SECRET_KEY, signature);
        if (!isValid) {
            httpResponse.setStatus(401); // 设置 HTTP 状态码
            httpResponse.setContentType("application/json"); // 设置返回类型为 JSON

            // 写入响应内容
            try (PrintWriter writer = httpResponse.getWriter()) {
                writer.write("{\"error\":\"Signature verification failure\"}");
                writer.flush();
            }
            throw new ServletException("签名验证失败");
        }


        // 签名验证通过，继续处理请求
        chain.doFilter(request, response);

    }

    @Override
    public void destroy() {
        // 可选择性实现清理逻辑
    }

    /**
     * 获取请求参数
     *
     * @param request HttpServletRequest
     * @return 参数的键值对
     */
    private Map<String, String> getRequestParams(HttpServletRequest request) {
        Map<String, String> params = new HashMap<>();
        request.getParameterMap().forEach((key, values) -> {
            if (values.length > 0) {
                params.put(key, values[0]);
            }
        });

        return params;
    }
}

